package cn.edu.gznu.wecampus.yqfkmj.framework.web.api;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.edu.gznu.wecampus.core.IRepository;
import cn.edu.gznu.wecampus.core.web.FormVo;
import cn.edu.gznu.wecampus.core.web.IAddRest;
import cn.edu.gznu.wecampus.core.web.IEditRest;
import cn.edu.gznu.wecampus.core.web.IFindAllRest;
import cn.edu.gznu.wecampus.core.web.IRemoveRest;
import cn.edu.gznu.wecampus.core.web.ISearch;
import cn.edu.gznu.wecampus.core.web.SearchVo;
import cn.edu.gznu.wecampus.core.web.annotation.SearchParam;
import cn.edu.gznu.wecampus.yqfkmj.framework.entity.Domitory;
import cn.edu.gznu.wecampus.yqfkmj.framework.entity.SchoolDistrict;
import cn.edu.gznu.wecampus.yqfkmj.framework.repository.DomitoryRepository;
import lombok.Getter;
import lombok.Setter;

@RestController
@RequestMapping("/api/domitory")
public class DomitoryApi implements
	ISearch<Domitory, String, DomitoryApi.DomitorySearchVo>,
	IAddRest<Domitory, String, DomitoryApi.DomitoryFormVo>,
	IEditRest<Domitory, String, DomitoryApi.DomitoryFormVo>,
	IFindAllRest<Domitory, String>,
	IRemoveRest<Domitory, String> {
	
	@Autowired
	private DomitoryRepository domitoryRepository;

	@Getter
	@Setter
	public static class DomitoryFormVo extends FormVo<String> {
		@Size(min = 1, message = "宿舍名称不能为空")
		private String name;
		@NotNull(message = "校区不能为空")
		private SchoolDistrict schoolDistrict;
	}
	
	@Getter
	@Setter
	public static class DomitorySearchVo extends SearchVo<Domitory, String> {
		@SearchParam(fields = {"name"}, operator = "like")
		private String name;
		@SearchParam(fields = {"schoolDistrict"}, operator = "in")
		private SchoolDistrict schoolDistrict;
		@SearchParam(fields = {"memberDomitories.xgh"}, operator = "like")
		private String xgh;
	}

	@Override
	public IRepository<Domitory, String> getRepository() {
		return domitoryRepository;
	}

	@Override
	public void processAddEntity(@Valid DomitoryFormVo form, Domitory entity) {
		entity.setName(form.getName());
		entity.setSchoolDistrict(form.getSchoolDistrict());
		domitoryRepository.saveAndFlush(entity);
	}

	@Override
	public void processEditEntity(@Valid DomitoryFormVo form, Domitory entity) {
		entity.setName(form.getName());
		entity.setSchoolDistrict(form.getSchoolDistrict());
		domitoryRepository.saveAndFlush(entity);
	}

	@Override
	public void processRemoveEntity(Domitory entity) {
		domitoryRepository.delete(entity);
	}
}
